package sequenceutil

import (
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	sequenceUtilLock sync.Mutex //同步锁
	seriesNum        = 0        //累计值
)

/**
* 取累计值(有代码锁)
* @param prefix 前缀
* @return
 */
func GetSeriesNum(prefix string) string {
	sequenceUtilLock.Lock() //加锁

	seriesNum = seriesNum + 1
	if seriesNum > 99 {
		seriesNum = 1
	}

	var build strings.Builder
	build.WriteString(strings.TrimSpace(prefix))

	str := strconv.Itoa(seriesNum)
	for i := len(str); i < 3; i++ {
		build.WriteString("0")
	}

	build.WriteString(str)

	sequenceUtilLock.Unlock() //解锁

	return build.String()
}

/**
* 取指定长度的流水号
* @param iMaxLength 指定长度
* @param prefix 前缀
* @return
 */
func GetSequence(iMaxLength int, prefix ...string) string {
	prefixStr := time.Now().Format("20060102150405")

	if len(prefix) > 0 {
		var build strings.Builder
		for _, val := range prefix {
			build.WriteString(strings.TrimSpace(val))
		}

		build.WriteString(prefixStr)
		prefixStr = build.String()
	}

	tmp := GetSeriesNum(prefixStr)

	if len(tmp) < iMaxLength {
		return tmp
	}

	return tmp[len(tmp)-iMaxLength : iMaxLength]
}

/**
* 取时间显示式的流水号
* @return 返回形式举例:20200521094216048001
 */
func Get() string {
	date := time.Now().Format("20060102150405")
	return GetSeriesNum(date)
}
